﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Kaskelot.Services.Model;

namespace Stockholm.SOA.Kaskelot.WCF.ServiceImplementation.Mapping
{
	public static class BlankettPostExtensions
	{
		public static DataContracts.BlankettPost ToContract(this BlankettPost entity)
		{
			DataContracts.BlankettPost b = new DataContracts.BlankettPost();

			CopyFromEntity(entity, b, false);

			return b;
		}

		public static DataContracts.BlankettPost ToMinimalContract(this BlankettPost entity)
		{
			DataContracts.BlankettPost b = new DataContracts.BlankettPost();

			CopyFromEntity(entity, b, true);

			return b;
		}

		public static BlankettPost ToEntity(this DataContracts.BlankettPost b)
		{
			BlankettPost entity = new BlankettPost();

			CopyToEntity(b, entity);

			return entity;
		}

		public static void UpdateEntity(this BlankettPost entity, DataContracts.BlankettPost blankettPost)
		{
			CopyToEntity(blankettPost, entity);
		}

		private static void CopyFromEntity(BlankettPost from, DataContracts.BlankettPost to, bool minimal)
		{
			to.Id = from.Id;
			to.ValId = from.ValId;
			to.Blankett = from.Blankett.ToMinimalContract();
			to.PersonId = from.PersonId;
			to.Andrad = from.Andrad;
			to.Skapad = from.Skapad;
			to.Status = from.Status;
			to.Motivering = from.Motivering;
			if (minimal)
				return;

			to.FaltData = from.FaltData.OrderBy(fd => fd.RadIndex).Select(fd => fd.ToContract()).ToList();
		}

		private static void CopyToEntity(DataContracts.BlankettPost from, BlankettPost to)
		{
			to.Id = from.Id;
			to.ValId = from.ValId;
			to.BlankettId = from.Blankett.Id;
			to.PersonId = from.PersonId;
			to.Andrad = from.Andrad;
			to.Skapad = from.Skapad;
			to.Status = from.Status;
			to.Motivering = from.Motivering;

			if (from.FaltData != null)
			{
				to.FaltData = from.FaltData.Select(f => f.ToEntity()).ToList();
			}
		}
	}
}
